package cn.tlb.gl.game.rebuild2;

import android.content.Context;
import android.opengl.GLSurfaceView;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/**
 * Created by 汤林冰 on 2016/1/12 11:45.
 */
public class ModelRenderer implements GLSurfaceView.Renderer{
    private GameModel gameModel;
    public ModelRenderer(final Context context){
        gameModel = new GameModel(context);
    }

    public void setGameModel(GameModel gameModel) {
        this.gameModel = gameModel;
    }

    @Override
        public void onSurfaceCreated(GL10 gl, EGLConfig config) {
            gl.glDisable(GL10.GL_DITHER);
            gl.glShadeModel(GL10.GL_SMOOTH);

            gl.glClearColor(0.2f, 0.2f, 0.2f, 0.3f);
            gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
            gl.glEnable(GL10.GL_DEPTH_TEST);
            gl.glDepthFunc(GL10.GL_LEQUAL);

            //启用2d纹理贴图
            gl.glEnable(GL10.GL_TEXTURE_2D);
            gameModel.loadTexture(gl);

            //启用opengl混合, 详见 http://dxwang.blog.51cto.com/384651/693834
            gl.glEnable(GL10.GL_BLEND);
            gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
        }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        gl.glViewport(0, 0, width, height);
        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();
        float ratio = (float)width/height;
        float y = 1;
        gl.glFrustumf(-ratio * y, ratio * y, -y, y, 1, 20);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        gl.glClear(GL10.GL_DEPTH_BUFFER_BIT | GL10.GL_COLOR_BUFFER_BIT);
        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

        gameModel.drawModel(gl);

        gl.glFinish();
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

        gameModel.updateAnimation();
    }

    public void setAngleX(float angleX) {
        gameModel.setAngleX(angleX);
    }

    public void setAngleY(float angleY) {
        gameModel.setAngleY(angleY);
    }
}
